from app.utils.diff_excel import compare_excel_files
from app.utils.validation import validate_file_upload
from app.utils.download_file import download_file
from app.error import FileDownloadError, ExcelProcessingError
import os
from loguru import logger


class ExcelService:
    @staticmethod
    def compare_excel_cells() -> tuple[bool, list]:
        """比对Excel单元格数据"""
        files = validate_file_upload(
            required_count=2, allowed_extensions=[".xlsx", ".xls"]
        )
        file1, file2 = files
        differences = compare_excel_files(file1, file2)
        if differences:
            logger.warning("文件存在差异: {}", differences)
            return False, differences
        logger.info("文件内容完全一致")
        return True, None

    @staticmethod
    def compare_download_excel_file(payload: dict) -> tuple[bool, list]:
        """下载并比较Excel文件"""
        validate_file_upload(required_count=0, allowed_extensions=[".xlsx", ".xls"])
        url = payload["url"]
        file = payload["path"]
        cookie = payload["cookie"]
        tax_type = payload["tax_type"]
        tax_org_number = payload["org_tax_num"]
        declare_month = payload["declare_month"]
        downloaded_path = download_file(
            url, cookie, file, tax_org_number, tax_type, declare_month
        )
        if not downloaded_path:
            logger.error("文件下载失败")
            raise FileDownloadError("下载失败", 400)
        logger.error("文件下载成功: {}", downloaded_path)
        old_file_path = os.path.join(
            os.path.dirname(downloaded_path), f"{tax_type}.xlsx"
        )
        return ExcelService._compare_files(downloaded_path, old_file_path)

    @staticmethod
    def _compare_files(file1: str, file2: str) -> tuple[bool, list]:
        """比较两个文件并返回结果"""
        differences = compare_excel_files(file1, file2)
        if differences:
            return False, differences
        logger.info("文件内容完全一致")
        return True, None
